<?php

namespace addons\zzuser\controller\api;

use app\common\controller\Api;
use app\common\library\Sms as S;
use GuzzleHttp\Client;
use think\Cache;
use think\Env;
use think\Validate;

class SetMobile extends Api
{
    protected $noNeedRight = 'index';

    public function index()
    {
        $validate = new Validate();
        if (!$validate->check(input(), [
            'mobile' => 'regex:^1\d{10}$',
            'sms'    => 'requireIf:mobile',
            'code'   => 'requireIf:mobile,""',
            'type'   => 'requireIf:code',
        ])) {
            $this->error($validate->getError());
        }
        $user   = $this->auth->getUser();
        $mobile = input('mobile');
        if ($mobile) {
            $sms = input('sms');
            if (!S::check($mobile, $sms)) {
                $this->error('error sms');
            }
            $user->save([
                'mobile' => $mobile,
            ]);
            $this->success();
        } else {
            $code = input('code');
            $type = input('type');
            if ($type == 'wechat') {
                $str = (new Client())->post('https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . self::access_token(), [
                    'json' => [
                        'code' => $code,
                    ],
                ])->getBody()->getContents();
                $arr = json_decode($str, true);
                if ($arr['errcode'] != 0) {
                    $this->error($arr['errmsg']);
                }
                $mobile = $arr['phone_info']['phoneNumber'];
                $user->save([
                    'mobile' => $mobile,
                ]);
                $this->success();
            }
            $this->error();
        }
    }

    private function access_token()
    {
        $key          = 'wechat_access_token';
        $access_token = Cache::get($key);
        if (!$access_token) {
            $app_id     = Env::get('wechat.miniapp_id');
            $app_secret = Env::get('wechat.miniapp_secret');
            $api        = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$app_id&secret=$app_secret";
            $str        = (new Client())->get($api)->getBody()->getContents();
            $arr        = json_decode($str, true);
            if (!isset($arr['access_token'])) {
                $this->error('服务器向微信获取access_token时发生错误');
            }
            $access_token = $arr['access_token'];
            $expires_in   = $arr['expires_in'];
            Cache::set($key, $access_token, $expires_in);
        }
        return $access_token;
    }
}
